package com.zjitc.controller;

import com.zjitc.beans.MessageBean;
import com.zjitc.common.ServerResponse;
import com.zjitc.common.redis.RedisCache;
import com.zjitc.pojo.User;
import com.zjitc.pojo.UserExtend;
import com.zjitc.service.UserService;
import com.zjitc.utils.old.FileUtils;
import com.zjitc.utils.old.Utils;
import com.zjitc.vo.user.ForgetPasswordDemo;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import sun.misc.BASE64Decoder;

import javax.imageio.ImageIO;
import javax.rmi.CORBA.Util;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

/**
 * @Author: xml
 * @Date: 2018/10/24 16:31
 * @Version 1.0
 */
@Controller
@RequestMapping("/user")
public class UserController extends BaseController {

    private final String MSG = "imageCode";
    private final String RSETKEY = "resetKey";
    private final String NULLSTR = "";
    @Autowired
    private UserService service;
    @Autowired
    private RedisCache redis;

    private static final Logger log = Logger.getLogger(UserController.class);

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<User> register(User user, String code, HttpSession session)
            throws UnsupportedEncodingException, NoSuchAlgorithmException {
        boolean flag = service.checkCode(user.getPhone(), code);
        if (flag) {
            User regiser = service.regiser(user);
            if (regiser == null) {
                return ServerResponse.createError("-2");
            }
            session.setAttribute("user", regiser);
            return ServerResponse.createSuccess();
        }
        return ServerResponse.createError("-1");
    }

    /**
     * 生成验证码
     */
    @RequestMapping("/code")
    public void code(HttpServletRequest request, HttpServletResponse response, HttpSession session)
            throws IOException {
        // 使用java图形界面技术绘制一张图片
        int charNum = 4;
        int width = 29 * 4;
        int height = 30;
        // 1. 创建一张内存图片
        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        // 2.获得绘图对象
        Graphics graphics = bufferedImage.getGraphics();
        // 3、绘制背景颜色
        graphics.setColor(new Color(255, 171, 147));
        graphics.fillRect(0, 0, width, height);
        // 4、绘制图片边框
        graphics.setColor(Color.WHITE);
        graphics.drawRect(0, 0, width - 1, height - 1);
        // 5、输出验证码内容
        graphics.setColor(Color.white);
        graphics.setFont(new Font("宋体", Font.BOLD, 24));
        // 随机输出4个字符
        Graphics2D graphics2d = (Graphics2D) graphics;
        String s = "ABCDEFGHGKLMNPQRSTUVWXYZ123456789";
        Random random = new Random();
        //session中要用到
        String msg = "";
        int x = 5;
        int four = 4;
        for (int i = 0; i < four; i++) {
            int index = random.nextInt(32);
            String content = String.valueOf(s.charAt(index));
            msg += content;
            double theta = random.nextInt(45) * Math.PI / 180;
            //让字体扭曲
            graphics2d.rotate(theta, x, 18);
            graphics2d.drawString(content, x, 18);
            graphics2d.rotate(-theta, x, 18);
            x += 29;
        }
        session.setAttribute(MSG, msg);
        // 释放资源
        graphics.dispose();
        // 图片输出 ImageIO
        ImageIO.write(bufferedImage, "jpg", response.getOutputStream());
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<User> login(String username, String password, HttpSession session) {
        return service.login(username, password, session);
    }


    @RequestMapping("/loginOut")
    public ModelAndView loginOut(HttpSession session) throws ServletException, IOException {
        session.removeAttribute("user");
        ModelAndView mv = new ModelAndView();
        mv.setViewName("redirect:/index.do");
        return mv;
    }

    @RequestMapping("/check")
    @ResponseBody
    public ServerResponse<User> check(String username) throws IOException {
        User user = service.checkUsername(username);
        if (user == null) {
            return ServerResponse.createSuccess();
        }
        return ServerResponse.createError();
    }

    @RequestMapping("/checkPassword")//没有用到
    @ResponseBody
    public ServerResponse checkpassword(String password, String uPassword) throws IOException {
        return service.checkpassword(password, uPassword);
    }


    @RequestMapping("searchmycollect")
    public ModelAndView searchMyCollect(HttpSession session,
                                        @RequestParam(value = "page", required = false, defaultValue = "0") String page) {
        return service.searchMyCollect(session, page);
    }

    @RequestMapping("sendPhoneCode")
    @ResponseBody
    public ServerResponse sendPhoneCode(String phone, HttpSession session) {
        return service.sendPhoneCode(phone, session);
    }

    @RequestMapping("/checkUser")
    @ResponseBody
    public Object checkUser(HttpSession session) {
        User user = getSessionUser(session);
        if (user != null) {
            return user;
        }
        return null;
    }

    @RequestMapping("/gotologin")
    public String indextologin() {
        return "/user/login";
    }

    @RequestMapping("/goto404")
    public ModelAndView goto404() {
        return new ModelAndView("404").addObject("error", 1);
    }

    @RequestMapping("/gotoregister")
    public String indextoregister() {
        return "/user/register";
    }


    /**
     * --------------------------------用户个人中心 及 修改----------------------------------
     */

    @RequestMapping("gotoUserMessage")
    public ModelAndView gotoUserMessage(HttpSession session) {
        ModelAndView modelAndView = new ModelAndView("404");
        User user = getSessionUser(session);
        if (user == null) {
            modelAndView.addObject("error", 1);
            return modelAndView;
        } else {
            modelAndView.setViewName("user/UserDetail");
            modelAndView.addObject("UserDetail", user);
            return modelAndView;
        }
    }


    @RequestMapping("/uploading")
    @ResponseBody
    public MessageBean updateMyHeadImg(String imgdatabase, HttpServletRequest request) {
        boolean flag = false;
        if (imgdatabase == null) {
            return new MessageBean(flag, "上传失败");
        }
        User sessionUser = getSessionUser(request.getSession());
        String path = request.getSession().getServletContext().getRealPath("") + "static\\img\\userImg\\";
        FileUtils.isMkDir(path);
        BASE64Decoder decoder = new BASE64Decoder();
        byte[] imgbyte;
        //        HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
        try {
            imgbyte = decoder.decodeBuffer(imgdatabase);
            String imgName = sessionUser.getUid();
            path = path + imgName + ".png";
            FileUtils.deleteFile(path);
            OutputStream os = new FileOutputStream(new File(path));
            os.write(imgbyte, 0, imgbyte.length);

            User userDetail = service.findbyuid(sessionUser.getUid());
            userDetail.setImg("/static/img/userImg/" + imgName + ".png");
            flag = service.update(userDetail);
            if (!flag) {
                return new MessageBean(flag, "上传失败");
            }
            os.close();
            return new MessageBean(flag, "上传成功");

        } catch (Exception e) {
            e.printStackTrace();
        }
        return new MessageBean(flag, "上传成功");
    }

    @RequestMapping("/updateUsername")
    @ResponseBody
    public MessageBean updatePhone(String username, HttpSession session) {
        User user = getSessionUser(session);
        if (user != null) {
            User user1 = service.findbyuid(user.getUid());
            user1.setUsername(username);
            boolean b = service.update(user1);
            if (b) {
                user.setUsername(username);
                setSessionUser(session, user);
                return new MessageBean(b, "修改成功");
            }
            return new MessageBean(b, "修改失败");
        }
        return new MessageBean(false, "用户认证已过期", -1);
    }

    @RequestMapping("/updatePhone")
    @ResponseBody
    public Object updatePhone(String phone, String phoneCode, HttpSession session) {
        String code = (String) redis.get(phone);
        boolean b = false;
        if (phoneCode.equals(code)) {
            User sessionUser = getSessionUser(session);
            User user = service.findbyuid(sessionUser.getUid());
            user.setPhone(phone);
            b = service.update(user);
            if (b) {
                sessionUser.setPhone(phone);
                setSessionUser(session, sessionUser);
                return new MessageBean(b, "");
            }
        }
        return new MessageBean(b, "验证码错误");
    }

    @RequestMapping("/updateSex")
    @ResponseBody
    public Object updateUserDetail(HttpSession session, String sex) {
        User user = getSessionUser(session);
        if (user != null) {
            User findbyuid = service.findbyuid(user.getUid());
            findbyuid.setSex(sex);
            boolean b = service.update(findbyuid);
            if (b) {
                user.setSex(sex);
                setSessionUser(session, user);
                return new MessageBean(b, "");
            }
            return new MessageBean(b, "修改错误");
        }
        return new MessageBean(false, "用户认证已过期", -1);
    }

    /**
     * --------------------------------修改密码   ----------------------------------
     */
    @RequestMapping("gotoResetPassword")
    public ModelAndView gotoResetPassword(HttpSession session, Integer page, @RequestParam(value = "key", required = false, defaultValue = "") String key) {
        User user = getSessionUser(session);
        ModelAndView modelAndView = new ModelAndView("404");
        if (user == null) {
            modelAndView.addObject("error", 1);
        } else {
            String userPhone = Utils.confident(user.getPhone());
            modelAndView.addObject("phone", userPhone);
            modelAndView.addObject("page", page);
            modelAndView.setViewName("/user/resetPassword");
        }
        if (!NULLSTR.equals(key)) {
            modelAndView.addObject("key", key);
        }
        return modelAndView;
    }

    @RequestMapping("resetPassword1")
    @ResponseBody
    public MessageBean resetPassword1(String code, String phone) {
        if (service.checkCode(phone, code)) {
            String key = Utils.code();
            redis.set(RSETKEY, key);
            redis.expire(RSETKEY, 300);
            return new MessageBean(true, key);
        }
        return new MessageBean(false, "");
    }

    @RequestMapping("resetPassword2")
    @ResponseBody
    public MessageBean resetPassword2(HttpSession session, String key, String password) {
        String resetKey = (String) redis.get(RSETKEY);
        if (key.equals(resetKey)) {
            User user = getSessionUser(session);
            try {
                service.updatePassword(user.getUid(), password);
            } catch (Exception e) {
                e.printStackTrace();
                return new MessageBean(false, "修改中出错，已中断修改", 1);
            }
            return new MessageBean(true, "修改成功");
        }
        return new MessageBean(false, "修改验证已过期，请重新验证", -1);
    }


    /**
     * --------------------------------忘记密码  全员post----------------------------------
     */

    @RequestMapping("/gotoForgetPassword")
    public ModelAndView gotoForgetPassword(Integer page) {
        ModelAndView modelAndView = new ModelAndView("/user/forgetPassword");
        modelAndView.addObject("page", page);
        return modelAndView;
    }

    @RequestMapping("/forgetPassword1")
    public ModelAndView forgetPasswordone(String username) {
        ModelAndView modelAndView = new ModelAndView("/user/forgetPassword");
        User user = service.checkUsername(username);
        user.setPassword("");
        modelAndView.addObject("user", user);
        modelAndView.addObject("page", 2);
        return modelAndView;
    }

    @RequestMapping("/forgetPassword2")
    @ResponseBody
    public boolean forgetPasswordtwo(String phone, String code) {
        return service.checkCode(phone, code);
    }

    @RequestMapping("/gotoforgetPassword3")
    public ModelAndView gotoforgetPasswordthree(String uid) {
        ModelAndView modelAndView = new ModelAndView("/user/forgetPassword");
        modelAndView.addObject("uid", uid);
        modelAndView.addObject("page", 3);
        return modelAndView;
    }

    @RequestMapping("/forgetPassword3")
    public ModelAndView forgetPasswordthree(String uid, String password) {
        boolean b = service.updatePassword(uid, password);
        if (b) {
            ModelAndView modelAndView = new ModelAndView("/user/forgetPassword");
            modelAndView.addObject("page", 4);
            return modelAndView;
        }
        return null;
    }
    //  ------------------------------------------------live--------------------------------------


//    @RequestMapping("/get/random")
//    @ResponseBody
//    public MessageBean randomUser(HttpSession session){
//        User user = getSessionUser(session);
//        if(user != null){
//            UserExtend extend = new UserExtend(user);
//            return new MessageBean(true,"请求成功",extend);
//        }else{
//            return new MessageBean(false,"请求失败");
//        }
//    }

}
